package com.zj.leetcode.easy.tree;

import java.util.TreeSet;

/**
 * @program: algorithm
 * @description: 二叉树中第二小的节点
 * 671 second-minimum-node-in-a-binary-tree
 * @author: Zhang Bo
 * @create: 2022-06-10 15:36:05
 **/
public class SecondMinimumNodeInABinaryTree {
    public static void main(String[] args) {
        Solution solution = new SecondMinimumNodeInABinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        TreeSet<Integer> set = new TreeSet<Integer>();
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null) {
                return -1;
            }
            if (root.left == null || root.right == null) {
                return -1;
            }
            this.dfs(root);
            if(set.size() >= 2){
                set.pollFirst();
                Integer res = set.pollFirst();
                return res;
            } else {
                return -1;
            }

        }


        public void dfs(TreeNode root) {
            if(root == null){
                return;
            }


            if(root.left != null){
                this.dfs(root.left);
                this.dfs(root.right);
            }

            set.add(root.val);

        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}

